<template>
  <div class="followAdd" v-loading="detailInfoShow">
    <div class="follow-info">
      <el-form
        :model="followForm"
        ref="followFormRef"
        :rules="queryRules"
        label-width="130px"
        v-enterToNext
      >
        <!-- :disabled="pageType === 'detail'" -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="实际开始时间：" prop="actualStartTime">
              <el-date-picker
                format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                v-model="followForm.actualStartTime"
                class="search-input"
                type="date"
                placeholder="请选择"
                @change="handleTimeChange(1)"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="实际结束时间：" prop="finishTime">
              <el-date-picker
                 format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                v-model="followForm.finishTime"
                class="search-input"
                type="date"
                placeholder="请选择"
                :default-time="new Date(2000, 1, 1, 23, 59, 59)"
                @change="handleTimeChange(2)"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="24">
          <el-form-item label="情况说明：">
            <el-input
              v-model="followForm.performance"
              type="textarea"
              :rows="5"
              maxlength="500"
              placeholder="请填写"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-row>
          <el-col :span="12">
            <el-form-item label="相关文档：">
              <Upload
                :fileList="followForm.ywImplProAddFileReqVos"
                :limit="5"
                limitation="templatelimitation"
                accept=".doc,.docx"
                :isFull="true"
                :isCanDelete="true"
                :showButton="true"
                @success="(result) => uploadSuccess(result)"
                @deleteFile="(result) => uploadRemove(result)"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 筛选按钮 -->
    <!-- v-if="pageType !== 'detail' && pageType !== 'check'" -->
    <div class="allbutton">
      <el-button
        style="color: #fff; background-color:#007CEF"
        @click="handleAddSave(followFormRef,1)"
        >完 成</el-button
      >
      <el-button
        style="color: #fff; background-color: rgba(67, 207, 124, 1)"
        @click="handleAddSave(followFormRef,0)"
        >保 存</el-button
      >
      
      <el-button style="background-color: #fff" @click="handleBack"
        >取 消</el-button
      >
    </div>

    <el-dialog
      :title="'跟进记录'"
      v-model="followshow"
      width="1400px"
      append-to-body
    >
      <Followdetail v-if="followshow" ref="followdetail"></Followdetail>
    </el-dialog>
  </div>
</template>

<script setup>
import Upload from "@/components/Upload/index";
import {
  getEndFollowApi,
  addFollowApi,
  getProjectApi,
} from "@/api/sales/project";
import { updatefollow } from "@/api/sales/marketing.js";
import Followdetail from "./followdetail";
import { getUserListApi } from "@/api/operation/work";
import { ElMessage, ElMessageBox } from "element-plus";
import { addSafeguardApi, editSafeguardApi } from "@/api/operation/protect";
import {
  getDenfenseList,
  projectReturnTaskApi,
  projectSubmitTaskApi,
  executeTaskInfoApi
} from "@/api/operation/project";

const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
  // 更新跟进组件显隐
  "update:renewalAddShow",
  //处理编辑
  "handleredit",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const followFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();

let followshow = ref(false);
//数据
let rowdata = ref({
  projectName: "",
  projectCode: "",
});
// 跟进表单引用
const followFormTemplate = {
  type:0,
  actualHour: null, // 	实际工时
  actualStartTime: "", // 实际开始时间
  businessId: null, // 业务ID
  businessType: null, // 业务类型erp_business_type(0:项目任务,1:工单申请,2:巡检计划,3:产品评估)
  finishTime: "", // 实际结束时间
  missionCenterId: null, // 任务中心id
  practiceStatus: null, // 实施状态erp_practice_status(0-待启动，1-待分配，2-进行中，3-已完结）用于完结项目
  workStandards: null, // 是否已勾选操作规范：0：否；1：是
  allotRelList: [], // 执行人
  endTime: "", // 	计划结束时间
  estimatedWorkHours: null, // 预估工时
  projectId: null, // 项目id
  performance: "", // 备注
  startTime: "", // 	计划开始时间
  taskType: null, // 	任务类型
  tableData: [],
  ywImplProAddFileReqVos: [], // 相关文件
  ywImplProInfoReqVos: [
    {
      suppFileInfoVos: [],
      suppFileInfoVos1: [], // 现场实地照片
      suppFileInfoVos2: [], // 外包用工合同
      suppFileInfoVos3: [], // 配件清单表
      suppFileInfoVos4: [], // 用电协议
      suppFileInfoVos5: [], // 现场完成照片
      suppFileInfoVos6: [], // 现场设备照片
      suppFileInfoVos7: [], // 物业租赁合同
    },
  ],
};
const data = reactive({
  // 跟进表单
  followForm: JSON.parse(JSON.stringify(followFormTemplate)),
  // 跟进表单校验规则
  queryRules: {
    actualStartTime: [
      { required: true, message: "请选择实际开始时间", trigger: "change" },
    ],
    finishTime: [
      { required: true, message: "请选择实际结束时间", trigger: "change" },
    ],
    
  },
  // 用户列表
  userList: [],
});
const { followForm, queryRules, userList } = toRefs(data);

/**
 * @description: 保存
 * @param {Object} followFormRef 跟进表单引用
 */
const handleAddSave = async (followFormRef,type) => {
  if (!followFormRef) return;
  await followFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          followForm.value.type = type
          let res = await projectSubmitTaskApi(followForm.value);
          if (res.code === 200) {
            emit("update:renewalAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  console.log(followForm.value)
  let fileType = 17;
  if(businessTypeName.value == '产品评估') {
    fileType = 23;
  }
  if(businessTypeName.value == '巡检计划') {
    fileType = 32;
  }
  if(businessTypeName.value == '工单申请') {
    fileType = 16;
  }
  followForm.value.ywImplProAddFileReqVos.push({ ...response, businessType: fileType });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  followForm.value.ywImplProAddFileReqVos.splice(index, 1);
}

/**
 * @description: 处理时间变更
 */
 const handleTimeChange = (flag) => {
  if (followForm.value.actualStartTime && followForm.value.finishTime &&followForm.value.actualStartTime > followForm.value.finishTime) {
    ElMessage.info("实际开始时间不能大于实际结束时间！");
    if (flag == 1) {
      followForm.value.actualStartTime = "";
    } else {
      followForm.value.finishTime = "";
    }
  }
};

/**
 * @description: 返回
 */
const handleBack = () => {
  ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      emit("update:renewalAddShow", false);
      followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
    })
    .catch(() => {});
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
// 名称
const businessTypeName  = ref('')
const handleDetailInfo = async (row) => {
  const res = await executeTaskInfoApi(row.missionCenterId)
  console.log('详情');
  console.log(res)

  businessTypeName.value = row.businessTypeName
  try {
    followForm.value.projectId = row.projectId;
    followForm.value.businessId = row.businessId;
    followForm.value.businessType = row.businessType;
    followForm.value.missionType = row.missionType;
    followForm.value.missionCenterId = row.missionCenterId;
    followForm.value.actualStartTime = res.taskInfoRespVo.actualStartTime
    followForm.value.finishTime = res.taskInfoRespVo.finishTime
    followForm.value.performance = res.taskInfoRespVo.performance
    followForm.value.ywImplProAddFileReqVos = res.taskInfoRespVo.suppFileInfoVos || []
    

    // followForm.value = { ...row, fileInfoVos: row.suppFileInfoVos || [] };
  } catch (error) {}
};

/**
 * @description: 获取用户列表
 */
const getUserList = async (id) => {
  await getUserListApi(2).then((res) => {
    if (res) {
      userList.value = res;
    }
  });
};

/**
 * @description: 处理跟进详情信息
 * @param {Number} id
 */
const followdetail = ref(null);
const handlerdetail = (row) => {
  followshow.value = true;
  setTimeout(() => {
    followdetail.value.handleDetailInfo({ ...row, ...rowdata.value });
  }, 100);
};

/**
 * @description: 处理编辑信息
 * @param {Number} id
 */
const handleredit = (row) => {
  console.log("执行");
  emit("handleredit", { ...row, ...rowdata.value });
};

let pageedit = ref("");
const editInfo = (data) => {
  console.log("编辑", data);
  rowdata.value = data;
  followForm.value = data;
  pageedit.value = "edit";
};

onMounted(() => {
  getUserList();
  if (props.pageType !== "detail" && props.pageType !== "check") {
    nextTick(() => {
      setTimeout(() => {
        refInput.value.focus();
      }, 800);
    });
  }
});

defineExpose({
  handleDetailInfo,
  editInfo,
});
</script>
<style lang="scss" scoped>
.followAdd {
  width: 100%;
  height: 100%;

  .follow-info {
    // padding: 20px 10px 5px 10px;
    // margin: 10px 0;
    height: 400px;
    .custom-textarea {
      :deep(.el-textarea__inner) {
        max-height: 200px !important; /* 你可以根据需要调整这个值 */
      }
    }
  }
  .follow-detail-info {
    margin-top: 20px;
    .table-operate {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #437dfb;
      .line {
        width: 1px;
        height: 20px;
        background-color: #437dfb;
      }
    }
  }
  .allbutton {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }
}
:deep(.el-collapse-item__arrow) {
  visibility: hidden;
}
</style>
<style lang="scss">
.followAdd {
  .el-popper.is-dark {
    max-width: 800px !important;
  }
}
.el-overlay-dialog {
  bottom: -6px !important;
}
</style>
